<?php
declare (strict_types = 1);

namespace daayu\taskload\service;

use daayu\taskload\TaskLoadConfig;

/**
 * 计划任务服务器Service层
 */
class TaskServerService extends BaseService
{
    protected $table = 'zn_task_server';

    public function listName(){
        return $this->table()->column('name', 'id');
    }

    public function list($args = [])
    {
        $page = isset($args['page']) ? intval($args['page']) : 1;
        $rows = isset($args['rows']) ? intval($args['rows']) : 20;
        $field = isset($args['field']) ? trim($args['field']) : 'id,name,key,describe,status,create_time,update_time';
        $orderBy = isset($args['order_by']) ? $args['order_by'] : 'id desc';
        $where = [];
        if(isset($args['id'])){
            if(is_array($args['id'])){
                $where[] = ['id', 'in', $args['id']];
            }elseif(intval($args['id']) > 0){
                $where[] = ['id', '=', intval($args['id'])];
            }
        }
        if(isset($args['name']) && !empty($args['name'])){
            $where[] = ['name', 'like', '%' . trim($args['name']) . '%'];
        }
        if(isset($args['status']) && $args['status'] > -1){
            $where[] = ['status', '=', intval($args['status'])];
        }
        $rs = $this->table()->where($where)->page($page, $rows)->field($field)->order($orderBy)->select()->toArray();
        if(!empty($rs)){
            foreach($rs as $k => &$v){
                if(isset($v['status'])){
                    $v['status_text'] = $this->status_names[$v['status']] ?? '';
                }
            }
        }
        $ret['total'] = isset($args['total']) ? $args['total'] : $this->table()->where($where)->count();
        $ret['page'] = $page;
        $ret['rows'] = $rs;
        return $ret;
    }

    public function listTask($args = [])
    {
        $server_id = $args['server_id'] ?? 0;
        if($server_id <= 0){
            $this->error = '必须指定服务器';
            return false;
        }
        $relate_project_ids = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_PROJECT)->where('server_id', $server_id)->column('project_id');
        if(empty($relate_project_ids)) return [];
        $relate_task_ids = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_RELATE)->where('server_id', $server_id)->column('task_id');
        $projects = $this->table(TaskLoadConfig::TABLE_TASK_PROJECT)->where('id', 'in', $relate_project_ids)->field('id,name,key,status')->select()->toArray();
        $task_rs = (new TaskPlanService($this->connection))->list(['rows'=>999, 'total'=>0, 'order_by'=>'id asc']);
        $tasks = $task_rs['rows'];
        foreach($projects as &$project){
            foreach ($tasks as $tk => $task) {
                if($project['id'] == $task['project_id']){
                    $task['is_on_server'] = 0;
                    if(in_array($task['id'], $relate_task_ids)) $task['is_on_server'] = 1;
                    if(!isset($project['tasks'])) $project['tasks'] = [];
                    $project['tasks'][] = $task;
                    unset($tasks[$tk]);
                }
            }
        }
        return $projects;
    }

    public function get($id, $field=null)
    {
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        $info = $this->table()->where('id', $id)->field($field)->find();
        if(!$info){
            $this->error = '指定的记录不存在';
            return false;
        }
        return $info;
    }

    public function save($data = [])
    {
        $id = 0;
        if(isset($data['id'])){
            $id = intval($data['id']);
            unset($data['id']);
            if(empty($id) || $this->table()->where('id', $id)->value('id') == null){
                $this->error = '指定的记录不存在';
                return false;
            }
        }
        //验证数据
        if(isset($data['name'])){
            $data['name'] = trim($data['name']);
            if(empty($data['name'])){
                $this->error = '服务器名称不能为空';
                return false;
            }
            $exist_id = $this->table()->where('name', '=', $data['name'])->where('id','not in', [$id])->value('id');
            if($exist_id){
                $this->error = '服务器名称不能重复';
                return false;
            }
            $data['key'] = md5($data['name']);
        }
        if(isset($data['describe'])){
            $data['describe'] = trim($data['describe']);
        }
        if(isset($data['status'])){
            $data['status'] = intval($data['status']);
            if(!in_array($data['status'], [0,1])){
                $this->error = '状态不正确，只能为[0,1]';
                return false;
            }
        }
        if($id > 0){
            $r = $this->table()->where('id', $id)->update($data);
        }else{
            $id = $this->table()->insertGetId($data);
        }
        return $id;
    }

    public function delete($id){
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        // 启动事务
        $this->db()->startTrans();
        try {
            $r = $this->table()->where('id', $id)->delete();
            //删除相关
            $r = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_PROJECT)->where('server_id', $id)->delete();
            $r = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_RELATE)->where('server_id', $id)->delete();
            // 提交事务
            $this->db()->commit();
            return $r;
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function createDb()
    {
        if(!$this->checkTable()){
            $sql = "CREATE TABLE `".$this->table."`  (
                `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
                `name` varchar(100) NULL DEFAULT '' COMMENT '服务器名字',
                `key` varchar(32) NULL DEFAULT '' COMMENT '服务器key',
                `status` tinyint(4) DEFAULT '0' COMMENT '状态 0禁用 1正常',
                `create_time` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
                `update_time` timestamp(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间',
                `describe` varchar(1000) NULL DEFAULT '' COMMENT '描述',
                `php_path` varchar(50) DEFAULT '' COMMENT 'php路径',
                `bash_path` varchar(50) DEFAULT '' COMMENT 'bash路径',
                `python_path` varchar(50) DEFAULT '' COMMENT 'python路径',
                `curl_path` varchar(50) DEFAULT '' COMMENT 'curl路径',
                PRIMARY KEY (`id`)
              ) ENGINE = InnoDB COMMENT = '服务器配置表' ROW_FORMAT = Dynamic";
            $this->db()->execute($sql);
        }
    }
}
